package com.flame.workflow.re.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.flame.workflow.re.entity.Node;
import com.flame.workflow.re.entity.Property;
import com.flame.workflow.re.mapper.NodeMapper;
import com.flame.workflow.re.mapper.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * flame_workflow_re_node 流程节点定义表
 *
 * @author 吴欣童
 * @since 2023-05-04 19:55:31
 */
@Service
public class NodeService {

    @Autowired
    private NodeMapper nodeMapper;

    @Autowired
    private PropertyMapper propertyMapper;

    public List<Node> getNodeList(Long modelId, Integer modelVersion) {
        return nodeMapper.listByModelId(modelId, modelVersion);
    }

    public void maintainNodeList(Long modelId, Integer modelVersion, List<Node> nodeList) {
        nodeMapper.deleteByModelId(modelId, modelVersion);
        for (Node node : nodeList) {
            node.setModelVersion(modelVersion);
            nodeMapper.insert(node);
        }
    }

    public List<Node> listByParentId(Long modelId, Integer modelVersion, Integer parentNodeId) {
        List<Node> nodeList = nodeMapper.findByParentId(modelId, modelVersion, parentNodeId);
        for (Node node : nodeList) {
            node.setNodeProperties(getNodeProperties(modelId, modelVersion, node.getNodeId()));
        }
        return nodeList;
    }

    public Node getNode(Long modelId, Integer modelVersion, Integer nodeId) {
        Node node = nodeMapper.findById(modelId, modelVersion, nodeId);
        node.setNodeProperties(getNodeProperties(modelId, modelVersion, nodeId));
        return node;
    }

    public Map<String, String> getNodeProperties(Long modelId, Integer modelVersion, Integer nodeId) {
        List<Property> properties = propertyMapper.listByObjectId(modelId, modelVersion, String.valueOf(nodeId));
        Map<String, String> nodeProperties = new HashMap<>();
        for (Property property : properties) {
            nodeProperties.put(property.getPropertyKey(), property.getPropertyValue());
        }
        return nodeProperties;
    }
}
